package org.geektimes.projects.user.web.controller.work;

import org.apache.commons.collections.CollectionUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.service.work.week01.impl.UserServiceImpl;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Logger;

import static org.geektimes.projects.user.service.work.week01.impl.UserServiceImpl.mapToObject;

/**
 * @program: user-platform
 * @description: 用户注册控制器
 * @author: magic_json
 * @create: 2021-02-28 12:26
 **/
@Path("/user")
public class RegisterController implements PageController {

    private static Logger logger = Logger.getLogger(RegisterController.class.getName());

    private UserServiceImpl userService = new UserServiceImpl();

    @GET
    @Path("/regView")
    public String registerView(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return "register-form.jsp";
    }

    @POST
    @Path("/register")
    public String register(HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean status = userService.register(getUserByParams(request));
        registerForward(request ,status);
        return "login-form.jsp";
    }

    @GET
    @Path("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        return "login-form.jsp";
    }


    /***
     * ======week02 part======
     */

    @Resource(name = "bean/UserService")
    private UserService userServiceBean;

    @Resource(name = "bean/Validator")
    private Validator beanValidator;

    @POST
    @Path("/registerByBean")
    public String registerByBean(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = getUserByParams(request);
        // id自增
//        long max = 100L;
//        long id = (long) (Math.random() * max);
//        user.setId(id);
        Set<ConstraintViolation<User>> violationSet =  beanValidator.validate(user);
        if(CollectionUtils.isNotEmpty(violationSet)){
            StringBuilder builder = new StringBuilder("注册用户信息校验失败，具体原因:");
            violationSet.forEach(violation -> builder
                    .append("\n")
                    .append("未通过字段:" + violation.getPropertyPath() + ":")
                    .append(violation.getMessage())
                    .append("\n"));
            request.getSession().setAttribute("error",builder.toString());
            return "error.jsp";
        }
        boolean status = userServiceBean.register(user);
        registerForward(request ,status);
        return "login-form.jsp";
    }

    private User getUserByParams(HttpServletRequest request) {
        Map params = request.getParameterMap();
        User user = null;
        if (Objects.nonNull(params)) {
            user = (User) mapToObject(params, User.class, "id");
        }
        return user;
    }

    private void  registerForward(HttpServletRequest request , boolean status){
        String registerStatus = "成功";
        if (!status) {
            registerStatus = "失败";
        }
        HttpSession session = request.getSession();
        session.setAttribute("registerStatus", "注册" + registerStatus);
    }

}

